<?php
namespace Data;

use Data\Drive\DataCache;
use Out;
use PDO;

class Insert extends \Data
{
    public static function Run($conf)
    {
        if (!is_array($conf)) {
            self::Error("插入参数必须为数组格式", __FILE__, __LINE__);
            Out::Error("插入参数必须为数组格式");
        }
        $sql  = self::toSql($conf);
        $num  = self::$db->exec($sql);
        $code = self::$db->errorCode();
        if ($code != 00000 || $num < 1) {
            $info = self::$db->errorInfo();
            self::Error(json_encode($info) . "\r\n" . $sql, __FILE__, __LINE__);
        }
        DataCache::clearCache($conf['table']);
        $id = self::$db->query("SELECT LAST_INSERT_ID() AS id")->fetch(PDO::FETCH_ASSOC);
        return ["state" => "ok", "msg" => "操作成功", "id" => $id['id']];
    }
    private static function toSql($conf)
    {
        $fields = implode("`,`", array_keys($conf['set']));
        $values = "'" . implode("','", array_values($conf['set'])) . "'";
        $values = preg_replace("/\'(-?[0-9]+\.?[0-9]+)\'/", "$1", $values);
        return "INSERT INTO {$conf['table']} (`{$fields}`) VALUES ({$values})";
    }
}
